import http from '@/utils/http';
import type { ApiResponse, ServerInfo } from '@/types';

// 应用统计数据类型
export interface AppStats {
  users: {
    total_users: number;
    admin_users: number;
    regular_users: number;
    new_users_today: number;
    new_users_week: number;
    new_users_month: number;
    active_users_today: number;
    active_users_week: number;
    growth_rate: string;
  };
  orders: {
    total_orders: number;
    paid_orders: number;
    pending_orders: number;
    failed_orders: number;
    completed_orders: number;
    cancelled_orders: number;
    total_revenue: number;
    revenue_today: number;
    revenue_week: number;
    revenue_month: number;
    avg_order_value: number;
    orders_today: number;
    orders_week: number;
    payment_success_rate: string;
    completion_rate: string;
  };
  products: {
    total_products: number;
    featured_products: number;
    recommended_products: number;
    active_products: number;
    inactive_products: number;
    new_products_week: number;
    new_products_month: number;
    avg_price: number;
    total_stock: number;
    low_stock_products: number;
    featured_rate: string;
    popular_products: Array<{
      id: number;
      name: string;
      price: number;
      is_featured: boolean;
      is_recommended: boolean;
      order_count: number;
      total_revenue: number;
    }>;
  };
  aiChat: {
    total_messages: number;
    active_chat_users: number;
    total_sessions: number;
    messages_today: number;
    messages_week: number;
    messages_month: number;
    user_messages: number;
    ai_responses: number;
    avg_messages_per_user: string;
    avg_messages_per_session: string;
  };
  credits: {
    total_credits: number;
    users_with_credits: number;
    avg_credits_per_user: number;
    low_credit_users: number;
    zero_credit_users: number;
    max_credits: number;
    min_credits: number;
  };
  ipGeoLocation: {
    overview: {
      total_unique_ips: number;
      total_ip_records: number;
      located_ips: number;
      new_ips_today: number;
      new_ips_week: number;
      location_rate: string;
    };
    provinces: Array<{
      province: string;
      unique_ips: number;
      total_records: number;
      unique_users: number;
      recent_records: number;
      user_conversion_rate: string;
    }>;
    cities: Array<{
      province: string;
      city: string;
      unique_ips: number;
      total_records: number;
      unique_users: number;
      user_conversion_rate: string;
    }>;
    mapVisualization: {
      provinces: Array<{
        name: string;
        province: string;
        value: number;
        visits: number;
        unique_ips: number;
        unique_users: number;
        logged_visits: number;
        login_rate: number;
        visit_density: number;
        user_conversion_rate: number;
        cities_array: string[];
      }>;
      summary: {
        total_provinces: number;
        total_visits: number;
        total_users: number;
        most_active_province: string;
        least_active_province: string;
      };
    };
  };
  websocket: {
    totalConnections: number;
    activeUsers: number;
    totalSessions: number;
  };
  server: {
    nodeVersion: string;
    platform: string;
    arch: string;
    pid: number;
    uptime: number;
    memoryUsage: {
      rss: number;
      heapTotal: number;
      heapUsed: number;
      external: number;
      arrayBuffers: number;
    };
  };
}

// DeepSeek信息类型
export interface DeepSeekInfo {
  balance: {
    is_available: boolean;
    api_status: string;
    currencies: Array<{
      currency: string;
      total_balance: number;
      granted_balance: number;
      topped_up_balance: number;
      balance_display: string;
    }>;
    total_balance_cny: string;
    total_balance_usd: string;
    status: string;
    last_updated: string;
  };
  usage: {
    total_requests: number;
    requests_today: number;
    requests_week: number;
    requests_month: number;
    requests_in_range: number;
    unique_users: number;
    unique_sessions: number;
    avg_requests_per_user: string;
    avg_requests_per_session: string;
    efficiency: {
      cost_per_request: string;
      requests_per_day_avg: string;
    };
    api_calls: {
      total_api_calls: number;
      calls_last_hour: number;
      calls_today: number;
      calls_week: number;
    };
    first_request: string;
    last_request: string;
  };
  service: {
    model: string;
    base_url: string;
    api_key_masked: string;
    status: string;
    last_check: string;
    health_indicators: {
      balance_sufficient: boolean;
      recent_activity: boolean;
      service_accessible: boolean;
    };
  };
  recommendations: {
    overall_status: string;
    warnings: string[];
    recommendations: string[];
    tips: string[];
  };
}

// 中国地图数据类型
export interface ChinaMapData {
  level: 'province' | 'city' | 'detail';
  mapData: Array<{
    name: string;              // 地图组件需要的名称
    province: string;
    city?: string;             // 城市级别时存在
    country?: string;          // 国家代码，城市级别时存在
    value: number;             // 地图显示的主要数值（用户数）
    visits: number;            // 访问次数
    unique_ips: number;        // 独立IP数
    unique_users: number;      // 独立用户数
    city_count?: number;       // 城市数量（省份级别时存在）
    login_rate: number;        // 登录转化率%
    visit_density: number;     // 访问密度
    user_conversion_rate: number; // 用户转化率%
  }>;
  summary: {
    total_provinces?: number;
    total_cities?: number;
    total_visits: number;
    total_users: number;
    total_unique_ips?: number;
    most_active_province?: string;
    most_active_city?: string;
  };
}

/**
 * 获取服务器信息
 */
export const getServerInfo = async (): Promise<ServerInfo> => {
  const response = await http.get('/admin/dashboard/server-info');
  return response.data.data;
};

/**
 * 获取应用统计信息
 */
export const getAppStats = async (timeRange: number = 30): Promise<AppStats> => {
  const response = await http.get('/admin/dashboard/app-stats', {
    params: { timeRange }
  });
  return response.data.data;
};

/**
 * 获取中国地图可视化数据
 */
export const getChinaMapData = async (params: {
  timeRange?: number;
  level?: 'province' | 'city' | 'detail';
  minVisits?: number;
}): Promise<ChinaMapData> => {
  const response = await http.get('/admin/dashboard/geo/china-map', { params });
  return response.data.data;
};

/**
 * 获取详细统计数据
 */
export const getDetailedStats = async (params: {
  startDate?: string;
  endDate?: string;
  groupBy?: 'day' | 'week' | 'month';
}): Promise<any> => {
  const response = await http.get('/admin/dashboard/stats/detailed', { params });
  return response.data.data;
};

/**
 * 获取DeepSeek详细信息
 */
export const getDeepSeekInfo = async (): Promise<DeepSeekInfo> => {
  const response = await http.get('/admin/dashboard/deepseek/balance');
  return response.data.data;
};

/**
 * 启动服务器监控
 */
export const startServerMonitor = async (): Promise<void> => {
  await http.post('/admin/dashboard/start-monitor');
};

/**
 * 停止服务器监控
 */
export const stopServerMonitor = async (): Promise<void> => {
  await http.post('/admin/dashboard/stop-monitor');
}; 